import React, { useEffect, useState, useRef } from 'react'
import styles from './index.module.less'
import { NavBar, Swiper, CenterPopup, Button, Toast, Dialog } from 'antd-mobile'
import { getgoodDatil, addCarts, addOrders } from '@/utils/cates'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { StarOutline } from 'antd-mobile-icons'
import { ImageViewer } from 'antd-mobile'
import { UserContactOutline, PictureWrongOutline } from 'antd-mobile-icons'
//数据仓库
import { saveColect, deletColect } from '@/store/colect'
import { useDispatch, useSelector } from 'react-redux'


export default function GoodsDetail() {
  //获取当前参数的id
  const [searchParams] = useSearchParams()
  //获取商品id
  const productId = searchParams.get('productId') as string | number
  //富文本数据
  const [source, setSource] = useState('')
  //富文本图片显示数据
  const [demoImages, setdemoImages] = useState<string[]>([])
  //购物车添加按钮的弹出框
  const [visible, setVisible] = useState(false)
  //sku 的数据
  let [skuList, setSkulist] = useState<any>([])
  //sku中的数据
  let [imgSrc, setimgSrc] = useState('')
  //库存
  let [stock, setstock] = useState(0)
  //找到富文本中所有图片
  function getImgSrc(richtext: string) {
    let imgList: string[] = [];
    richtext.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, (match, capture): any => {
      imgList.push(capture);
    });
    return imgList;
  }
  //详情页数据
  const [detailsData, setData] = useState<any>({})
  //轮播图图片
  const [swiperList, setSwiper] = useState<any[]>([])
  //收藏按钮标志
  const colectitem = useSelector((state: { colect: { colectList: [] } }) => state.colect.colectList)
  console.log(colectitem);

  //请求详情页所有数据
  async function getdatialGood(id: string | number) {
    let res: resType = await getgoodDatil(id)
    // console.log(res);
    if (res.code === 20000) {
      console.log(res.data.product);
      //判断是否是已收藏按钮
      (colectitem && colectitem.find((item: { id: string }) => item.id === res.data.product.id)) ?
        res.data.product.colectstar = true : res.data.product.colectstar = false
      //如果是已经收藏的商品，直接给是否收藏标志状态
      setflag(res.data.product.colectstar)
      let sku = res.data.product.skuList
      sku = sku.map((item: { spData: string }) => {
        item.spData = JSON.parse(item.spData)
        return item
      });


      if (sku.length) {
        setSkulist(sku)
        setkeyss(sku[0].id)
        //头部的数据
        setimgSrc(res.data.product.skuList[0].pic)
        //库存
        setstock(res.data.product.skuList[0].stock)
      }




      //设置详情页数据
      setData(res.data.product)
      // detail = res.data.product

      //轮播图数据处理
      let imglist: string[] = [res.data.product.pic, ...res.data.product.albumPics.split(',')]
      setSwiper(imglist)
      //富文本数据
      let richtext = res.data.product.detailMobileHtml.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;"')
      const demoImages = getImgSrc(richtext)
      setdemoImages(demoImages)
      setSource(richtext)
    }
  }
  useEffect(() => {
    getdatialGood(productId)
  }, [])
  //点击返回上一页
  const back = () => window.history.back()
  //轮播图单项数据
  const items = swiperList.map((item, index) => (
    <Swiper.Item key={index}>
      <div className={styles.content}>
        <img src={item} alt="" />
      </div>
    </Swiper.Item>
  ))
  //富文本图片点击事件
  function richTextClick(event: any) {
    if (event.target.nodeName === 'IMG' || event.target.nodeName === 'img') { // 标签名
      const img = event.target.currentSrc; // 图片路径
      let index = demoImages.findIndex(item => item === img)
      ImageViewer.Multi.show({ images: demoImages, defaultIndex: index })
    }
  }

  let [types, setTypes] = useState(1)
  //添加购物车和立即购买调用的是相同的点击事件，val ==1 是添加功能，val=0 是立即购买功能
  function addcart(val: number) {
    stock ? setVisible(true) : Toast.show({ content: '暂无库存,请联系商家' })
    setTypes(val)
  }
  //sku中的点击切换
  let [keyss, setkeyss] = useState('')
  let [count, setcount] = useState(1)
  //sku选择
  function checkSku(ids: string) {
    //当前点击项的key
    setkeyss(ids)
    console.log(ids);
    let aaa = skuList.find((item: { id: string }) => item.id === ids)
    setimgSrc(aaa.pic)
    setstock(aaa.stock)
  }
  //添加购物车或者立即购买
  const navgite = useNavigate()
  async function addCartsubmit() {
    //判断本地是否具有token 如果有直接进行下一步，如果没有直接弹出对话框
    if (localStorage.getItem('token')) {
      if (types) {
        console.log('添加购物车');
        let data = {
          cartId: "",
          productId: detailsData.id,
          productSkuId: keyss,
          quantity: count,
        }
        let res: resType = await addCarts(data)

        if (res.code === 20000) {
          Toast.show({
            icon: 'success',
            content: '添加成功'
          })
          setVisible(false)
        }
      } else {

        let orderItemList = [{
          productId: detailsData.id,
          productQuantity: count,
          productSkuId: keyss,
        }]

        let res: resType = await addOrders({ orderItemList })
        if (res.code === 20000) {
          setVisible(false)
          navgite("/my/order/confirmorder?id=" + res.data.orderId)
        }
      }
    } else {
      Dialog.confirm({
        title: '是否登录',
        content: '暂未登录，是否立即登录',
        onConfirm: async () => {
          navgite("/my/login")
          setVisible(false)
        },
        onCancel: async () => {
          Toast.show({
            icon: 'waning',
            content: '取消成功'
          })
        },
      })

    }
  }
  const dispatch = useDispatch()

  let [flag, setflag] = useState(false)
  // 提示
  function colectClick() {
    let falgs = !flag

    setData({
      ...detailsData,
      colectstar: falgs
    })
    setflag(!flag)
    Toast.show({
      icon: 'success',
      content: falgs ? '收藏成功' : '取消收藏成功'
    })
    falgs ? dispatch(saveColect(detailsData)) : dispatch(deletColect(detailsData))

  }
  return (
    <div  >
      <NavBar onBack={back} className={styles.topNav}>{detailsData.name}</NavBar>
      {/* 商品轮播图 */}
      <div className={styles.topBox} >
        <div className={styles.swiperBox}>
          {
            swiperList.length && <Swiper indicatorProps={{ color: 'white', }} loop>{items}</Swiper>
          }
        </div>
        <div className={styles.collectbox}>
          <StarOutline onClick={colectClick} className={[styles.starts, detailsData.colectstar ? styles.startactive : ''].join(' ')} />
        </div>
      </div>
      {/* 商品标题   */}
      {JSON.stringify(detailsData) !== "{}" &&
        <div className={styles.contentsa}>
          <div className={styles.goodsName}>
            <div className={styles.goodPrice}>
              {
                detailsData.promotionPrice ? (
                  <div>
                    <span className={styles.fontsizds}>
                      <span className={styles.pricelist}>￥</span>
                      <span className={styles.pricePreint}> {parseInt(detailsData.promotionPrice)}</span>
                      {(detailsData.promotionPrice+'').split('.')[1] ?  <span>.{(detailsData.promotionPrice+'').split('.')[1]} </span>:<span>.00</span>}
                      {/* {(detailsData.promotionPrice % parseInt(detailsData.promotionPrice) + '').split('.')[1] ? <span>.{(detailsData.promotionPrice / parseInt(detailsData.promotionPrice) + '').split('.')[1]}</span> : <span>.00</span>} */}
                    </span>
                    {detailsData.price &&
                      <span className={styles.priceBox}>
                        ￥{detailsData.price} {detailsData.price % parseInt(detailsData.price) ? '' : <span>.00</span>
                        }
                      </span>
                    }
                  </div>
                ) : <span className={styles.fontsizds}>
                  <span className={styles.pricelist}>￥</span>
                  <span className={styles.pricePreint}> {parseInt(detailsData.price)}</span>
                  {(detailsData.price + '').split('.')[1] ? <span>.{(detailsData.price + '').split('.')[1]}</span> : <span>.00</span>}
                </span>
              }
            </div>
            <div className={styles.coutent}>没有促销使用原价</div>
          </div>
          <div className={styles.goodstitel}>{detailsData.detailTitle}</div>
          <div className={styles.goodInstrcter}>{detailsData.description}</div>
          <div className={styles.detaili}
            onClick={richTextClick}
            dangerouslySetInnerHTML={{ __html: source }}
          >

          </div>
        </div>}
      <div className={styles.bottomfooter}>
        <div className={styles.customers}><UserContactOutline /></div>
        <div className={styles.addcart} onClick={() => addcart(1)}>添加到购物车</div>
        <div className={styles.payOrder} onClick={() => addcart(0)}>立即购买</div>
      </div>
      {/* //弹出框 */}
      <div>
        <CenterPopup
          visible={visible}
          onMaskClick={() => {
            setVisible(false)
          }}
        >
          <div className={styles.cartbox}>
            <div style={{ display: 'flex' }}>
              <div className={styles.imgbox}>
                {/* <img src={imgSrc} alt="logo" /> */}
                {
                  imgSrc ?
                    <img src={imgSrc} alt="" /> :
                    <div>
                      <PictureWrongOutline fontSize={36} />
                    </div>
                }
              </div>
              <div className={styles.goodDtail}>
                <div style={{ fontWeight: 'bold' }}>{detailsData.name}</div>
                <div className={styles.stockCount}>商品库存：{stock}</div>
              </div>
            </div>
            <div className={styles.skuList}>
              <div style={{ fontWeight: 'bold' }}>商品选择</div>
              <div >
                {skuList.length &&
                  skuList.map((item: { spData: [], id: string }) => <div key={item.id}
                    onClick={() =>
                      checkSku(item.id)}
                    className={
                      [
                        styles.skuItems, keyss === item.id ? styles.active : ''
                      ].join(' ')
                    }
                  >
                    {item.spData.map((items: { key: string, value: string }, index) =>
                      <div key={index} >
                        {`${items.key}:${items.value}`}
                      </div>
                    )
                    }
                  </div>)
                }

              </div>
            </div>
            <div className={styles.skuList}>
              <div style={{ fontWeight: 'bold' }}>特色服务</div>
              <div  >
                <div className={styles.skuItems}>
                  送货上门
                </div>
                <div className={styles.skuItems}>
                  上门安装
                </div>
              </div>
            </div>
            <div className={styles.cartcount}>
              <div style={{ fontWeight: 'bold' }}>购买数量</div>
              <div className={styles.countDIv}>
                <div onClick={() => {
                  if (count > 1) {
                    setcount(count - 1)
                  } else {
                    Toast.show({
                      content: '不能更少了！！'
                    })
                  }
                }}  >-</div>
                <div>{count}</div>
                <div onClick={() => {
                  if (count < stock) {

                    setcount(count + 1)
                  } else {
                    Toast.show({
                      content: '库存不够了！！'
                    })
                  }
                }}  >+</div>
              </div>
            </div>
            <div className={styles.sumitBox} >
              <Button className={styles.sumitBtss} onClick={addCartsubmit} color='primary' fill='solid'>
                确定
              </Button>
            </div>
          </div>
        </CenterPopup>
      </div >
    </div >
  )
}
